<template>
  <div class="page-box">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-value">{{ statsData.total_commission || 0 }}</div>
            <div class="stats-label">总佣金金额</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-value">{{ statsData.pending_commission || 0 }}</div>
            <div class="stats-label">待结算佣金</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-value">{{ statsData.settled_commission || 0 }}</div>
            <div class="stats-label">已结算佣金</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-value">{{ statsData.settlement_count || 0 }}</div>
            <div class="stats-label">结算笔数</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 标签页切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 佣金记录 -->
      <el-tab-pane label="佣金记录" name="commission">
        <universal-table
          :columns="commissionColumns"
          :fetch-data="fetchCommissionData"
          permission-prefix="sys:nfc_commission"
          :show-selection="true"
          :show-index="true"
          :show-operation="true"
          :operation-width="'200'"
          :bt1-name="''"
          :bt2-name="''"
          :export-file-name="'NFC佣金记录'"
          :init-search-form="{}"
          :custom-export="true"
          :show-keyword-search="false"
          :showDateRange="false"
          @edit="handleEdit"
          @delete="handleDelete"
          @reset="resetCommissionSearch"
          @selection-change="handleCommissionSelectionChange"
          @custom-export="handleExportCommission"
          ref="commissionTable">

          <!-- 搜索区域扩展 -->
          <template #searchExtend>
            <el-form-item prop="merchant_id">
              <el-input v-model="commissionSearchForm.merchant_id" placeholder="商户ID" type="number"></el-input>
            </el-form-item>

            <el-form-item prop="campaign_id">
              <el-input v-model="commissionSearchForm.campaign_id" placeholder="活动ID" type="number"></el-input>
            </el-form-item>

            <el-form-item prop="settlement_status">
              <el-select v-model="commissionSearchForm.settlement_status" placeholder="结算状态" clearable>
                <el-option label="待结算" value="0"></el-option>
                <el-option label="处理中" value="1"></el-option>
                <el-option label="已结算" value="2"></el-option>
                <el-option label="结算失败" value="3"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="amount_range">
              <el-input v-model="commissionSearchForm.min_amount" placeholder="最低金额" type="number" style="width: 100px;"></el-input>
              <span style="margin: 0 10px;">-</span>
              <el-input v-model="commissionSearchForm.max_amount" placeholder="最高金额" type="number" style="width: 100px;"></el-input>
            </el-form-item>

            <el-form-item prop="created_date_range">
              <el-date-picker
                v-model="commissionCreatedDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="产生开始时间"
                end-placeholder="产生结束时间"
                value-format="yyyy-MM-dd"
                @change="handleCommissionCreatedDateRangeChange">
              </el-date-picker>
            </el-form-item>

            <el-form-item prop="settled_date_range">
              <el-date-picker
                v-model="commissionSettledDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="结算开始时间"
                end-placeholder="结算结束时间"
                value-format="yyyy-MM-dd"
                @change="handleCommissionSettledDateRangeChange">
              </el-date-picker>
            </el-form-item>

            <!-- 批量操作按钮 -->
            <el-form-item>
              <el-button type="primary" @click="handleRefreshCommission">
                <i class="el-icon-refresh"></i> 刷新
              </el-button>
            </el-form-item>
          </template>

          <!-- 操作栏扩展 -->
          <template #operationExtend="{ row }">
            <el-tooltip content="查看详情" placement="top">
              <el-button size="mini" type="info" icon="el-icon-view" @click="handleViewCommissionDetail(row)" circle></el-button>
            </el-tooltip>
          </template>
        </universal-table>
      </el-tab-pane>

      <!-- 结算管理 -->
      <el-tab-pane label="结算管理" name="settlement">
        <div class="settlement-actions">
          <el-button type="primary" icon="el-icon-plus" @click="handleCreateSettlement">
            创建结算单
          </el-button>
        </div>

        <universal-table
          :columns="settlementColumns"
          :fetch-data="fetchSettlementData"
          permission-prefix="sys:nfc_settlement"
          :show-selection="true"
          :show-index="true"
          :show-operation="true"
          :operation-width="'280'"
          :bt1-name="''"
          :bt2-name="''"
          :export-file-name="'NFC结算记录'"
          :init-search-form="{}"
          :custom-export="true"
          :show-keyword-search="false"
          @edit="handleEdit"
          @delete="handleDelete"
          @reset="resetSettlementSearch"
          @selection-change="handleSettlementSelectionChange"
          @custom-export="handleExportSettlement"
          ref="settlementTable">

          <!-- 搜索区域扩展 -->
          <template #searchExtend>
            <el-form-item prop="merchant_id">
              <el-input v-model="settlementSearchForm.merchant_id" placeholder="商户ID" type="number"></el-input>
            </el-form-item>

            <el-form-item prop="settlement_status">
              <el-select v-model="settlementSearchForm.settlement_status" placeholder="结算状态" clearable>
                <el-option label="待处理" value="0"></el-option>
                <el-option label="处理中" value="1"></el-option>
                <el-option label="已完成" value="2"></el-option>
                <el-option label="已失败" value="3"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="settlement_period">
              <el-select v-model="settlementSearchForm.settlement_period" placeholder="结算周期" clearable>
                <el-option label="日结" value="daily"></el-option>
                <el-option label="周结" value="weekly"></el-option>
                <el-option label="月结" value="monthly"></el-option>
                <el-option label="季结" value="quarterly"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="date_range">
              <el-date-picker
                v-model="settlementDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                @change="handleSettlementDateRangeChange">
              </el-date-picker>
            </el-form-item>

            <!-- 批量操作按钮 -->
            <el-form-item>
              <el-button type="primary" @click="handleRefreshSettlement">
                <i class="el-icon-refresh"></i> 刷新
              </el-button>
            </el-form-item>
          </template>

          <!-- 操作栏扩展 -->
          <template #operationExtend="{ row }">
            <el-tooltip content="查看详情" placement="top">
              <el-button size="mini" type="info" icon="el-icon-view" @click="handleViewSettlementDetail(row)" circle></el-button>
            </el-tooltip>
            <el-tooltip content="处理结算" placement="top" v-if="row.settlement_status == 0">
              <el-button size="mini" type="primary" icon="el-icon-check" @click="handleProcessSettlement(row)" circle></el-button>
            </el-tooltip>
            <el-tooltip content="完成结算" placement="top" v-if="row.settlement_status == 1">
              <el-button size="mini" type="success" icon="el-icon-finished" @click="handleCompleteSettlement(row)" circle></el-button>
            </el-tooltip>
            <el-tooltip content="取消结算" placement="top" v-if="[0, 1].includes(row.settlement_status)">
              <el-button size="mini" type="danger" icon="el-icon-close" @click="handleCancelSettlement(row)" circle></el-button>
            </el-tooltip>
          </template>
        </universal-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建结算单对话框 -->
    <el-dialog title="创建结算单" :visible.sync="createSettlementDialogVisible" width="600px" @close="resetCreateSettlementForm">
      <el-form :model="createSettlementForm" :rules="createSettlementRules" ref="createSettlementForm" label-width="120px">
        <el-form-item label="商户ID" prop="merchant_id">
          <el-input
            v-model="createSettlementForm.merchant_id"
            type="number"
            placeholder="请输入商户ID">
          </el-input>
        </el-form-item>
        <el-form-item label="结算周期" prop="settlement_period">
          <el-select v-model="createSettlementForm.settlement_period" placeholder="请选择结算周期">
            <el-option label="日结" value="daily"></el-option>
            <el-option label="周结" value="weekly"></el-option>
            <el-option label="月结" value="monthly"></el-option>
            <el-option label="季结" value="quarterly"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动ID" prop="campaign_id">
          <el-input
            v-model="createSettlementForm.campaign_id"
            type="number"
            placeholder="请输入活动ID（可选）">
          </el-input>
        </el-form-item>
        <el-form-item label="日期范围" prop="date_range">
          <el-date-picker
            v-model="createSettlementDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleCreateSettlementDateRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="允许空结算">
          <el-switch v-model="createSettlementForm.allow_empty"></el-switch>
          <div class="form-tip">开启后，即使没有待结算佣金也可以创建结算单</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createSettlementDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCreateSettlement" :loading="createSettlementLoading">确定创建</el-button>
      </div>
    </el-dialog>

    <!-- 结算详情对话框 -->
    <el-dialog title="结算单详情" :visible.sync="settlementDetailDialogVisible" width="900px">
      <div v-if="currentSettlement">
        <!-- 结算单基本信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>结算单ID：</label>
              <span>{{ currentSettlement.id }}</span>
            </div>
            <div class="detail-item">
              <label>商户名称：</label>
              <span>{{ currentSettlement.merchant_name }}</span>
            </div>
            <div class="detail-item">
              <label>结算金额：</label>
              <span class="amount">¥{{ currentSettlement.settlement_amount }}</span>
            </div>
            <div class="detail-item">
              <label>佣金数量：</label>
              <span>{{ currentSettlement.commission_count }}笔</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>结算周期：</label>
              <span>{{ getSettlementPeriodText(currentSettlement.settlement_period) }}</span>
            </div>
            <div class="detail-item">
              <label>结算状态：</label>
              <el-tag :type="getSettlementStatusTagType(currentSettlement.settlement_status)">
                {{ getSettlementStatusText(currentSettlement.settlement_status) }}
              </el-tag>
            </div>
            <div class="detail-item">
              <label>创建时间：</label>
              <span>{{ currentSettlement.create_time }}</span>
            </div>
            <div class="detail-item">
              <label>处理时间：</label>
              <span>{{ currentSettlement.processed_at || '-' }}</span>
            </div>
          </el-col>
        </el-row>

        <!-- 佣金记录列表 -->
        <el-divider content-position="left">相关佣金记录</el-divider>
        <el-table :data="settlementCommissions" size="small" max-height="400">
          <el-table-column prop="id" label="记录ID" width="80"></el-table-column>
          <el-table-column prop="campaign_name" label="活动名称" width="150"></el-table-column>
          <el-table-column prop="user_id" label="用户ID" width="80"></el-table-column>
          <el-table-column prop="commission_amount" label="佣金金额" width="100">
            <template slot-scope="scope">
              <span class="amount">¥{{ scope.row.commission_amount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="commission_rate" label="佣金率" width="80">
            <template slot-scope="scope">
              {{ scope.row.commission_rate }}%
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="产生时间" width="160"></el-table-column>
          <el-table-column prop="settled_at" label="结算时间" width="160"></el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 处理结算对话框 -->
    <el-dialog title="处理结算" :visible.sync="processSettlementDialogVisible" width="500px">
      <div v-if="currentSettlement">
        <el-alert
          title="处理结算将从商户保证金中扣除相应金额"
          type="warning"
          :closable="false"
          show-icon>
        </el-alert>
        <div style="margin: 20px 0;">
          <div class="detail-item">
            <label>结算单ID：</label>
            <span>{{ currentSettlement.id }}</span>
          </div>
          <div class="detail-item">
            <label>商户名称：</label>
            <span>{{ currentSettlement.merchant_name }}</span>
          </div>
          <div class="detail-item">
            <label>结算金额：</label>
            <span class="amount">¥{{ currentSettlement.settlement_amount }}</span>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processSettlementDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProcessSettlement" :loading="processSettlementLoading">确定处理</el-button>
      </div>
    </el-dialog>

    <!-- 完成结算对话框 -->
    <el-dialog title="完成结算" :visible.sync="completeSettlementDialogVisible" width="500px" @close="resetCompleteSettlementForm">
      <el-form :model="completeSettlementForm" ref="completeSettlementForm" label-width="100px">
        <div v-if="currentSettlement">
          <div class="detail-item">
            <label>结算单ID：</label>
            <span>{{ currentSettlement.id }}</span>
          </div>
          <div class="detail-item">
            <label>商户名称：</label>
            <span>{{ currentSettlement.merchant_name }}</span>
          </div>
          <div class="detail-item">
            <label>结算金额：</label>
            <span class="amount">¥{{ currentSettlement.settlement_amount }}</span>
          </div>
        </div>
        <el-form-item label="完成备注" prop="remark">
          <el-input
            v-model="completeSettlementForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入完成备注（可选）"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="completeSettlementDialogVisible = false">取消</el-button>
        <el-button type="success" @click="confirmCompleteSettlement" :loading="completeSettlementLoading">确定完成</el-button>
      </div>
    </el-dialog>

    <!-- 取消结算对话框 -->
    <el-dialog title="取消结算" :visible.sync="cancelSettlementDialogVisible" width="500px" @close="resetCancelSettlementForm">
      <el-form :model="cancelSettlementForm" :rules="cancelSettlementRules" ref="cancelSettlementForm" label-width="100px">
        <div v-if="currentSettlement">
          <div class="detail-item">
            <label>结算单ID：</label>
            <span>{{ currentSettlement.id }}</span>
          </div>
          <div class="detail-item">
            <label>商户名称：</label>
            <span>{{ currentSettlement.merchant_name }}</span>
          </div>
          <div class="detail-item">
            <label>结算金额：</label>
            <span class="amount">¥{{ currentSettlement.settlement_amount }}</span>
          </div>
        </div>
        <el-form-item label="取消原因" prop="reason">
          <el-input
            v-model="cancelSettlementForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入取消原因"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSettlementDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmCancelSettlement" :loading="cancelSettlementLoading">确定取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import UniversalTable from "@/components/TableComponent.vue";
import { nfcCommissionAPI } from '@/api/nfc'
import { handleCSVExportResponse } from '@/utils/exportCSV'

export default {
  name: 'NfcCommissionManagement',
  components: { UniversalTable },
  data() {
    return {
      activeTab: 'commission',
      
      // 统计数据
      statsData: {},

      // 佣金记录表格
      commissionColumns: [
        { prop: 'id', label: '记录ID', width: 80 },
        { prop: 'merchant_id', label: '商户ID', width: 100 },
        { prop: 'merchant_name', label: '商户名称', width: 180 },
        { prop: 'campaign_id', label: '活动ID', width: 80 },
        { prop: 'campaign_name', label: '活动名称', width: 150 },
        { prop: 'user_id', label: '用户ID', width: 80 },
        { 
          prop: 'commission_amount', 
          label: '佣金金额', 
          width: 120,
          render: (h, { row }) => {
            return h('span', {
              class: 'amount-text'
            }, `¥${row.commission_amount}`)
          }
        },
        { 
          prop: 'commission_rate', 
          label: '佣金率', 
          width: 80,
          render: (h, { row }) => {
            return h('span', `${row.commission_rate}%`)
          }
        },
        {
          prop: 'settlement_status_text',
          label: '结算状态',
          width: 120,
          render: (h, { row }) => {
            return h('el-tag', {
              props: {
                type: this.getCommissionStatusTagType(row.settlement_id, row.settlement_status),
                size: 'mini'
              }
            }, row.settlement_status_text)
          }
        },
        { prop: 'settlement_id', label: '结算单ID', width: 100 },
        { prop: 'create_time', label: '产生时间', width: 160 },
        { prop: 'settled_at', label: '结算时间', width: 160 }
      ],

      // 结算记录表格
      settlementColumns: [
        { prop: 'id', label: '结算单ID', width: 100 },
        { prop: 'merchant_id', label: '商户ID', width: 100 },
        { prop: 'merchant_name', label: '商户名称', width: 180 },
        { 
          prop: 'settlement_amount', 
          label: '结算金额', 
          width: 120,
          render: (h, { row }) => {
            return h('span', {
              class: 'amount-text'
            }, `¥${row.settlement_amount}`)
          }
        },
        { prop: 'commission_count', label: '佣金数量', width: 100 },
        { prop: 'settlement_period', label: '结算周期', width: 100 },
        {
          prop: 'settlement_status',
          label: '状态',
          width: 100,
          render: (h, { row }) => {
            return h('el-tag', {
              props: {
                type: this.getSettlementStatusTagType(row.settlement_status),
                size: 'mini'
              }
            }, this.getSettlementStatusText(row.settlement_status))
          }
        },
        { prop: 'create_time', label: '创建时间', width: 160 },
        { prop: 'processed_at', label: '处理时间', width: 160 },
        { prop: 'completed_at', label: '完成时间', width: 160 }
      ],

      // 搜索表单
      commissionSearchForm: {
        merchant_id: '',
        campaign_id: '',
        settlement_status: '',
        min_amount: '',
        max_amount: '',
        created_start_date: '',
        created_end_date: '',
        settled_start_date: '',
        settled_end_date: ''
      },
      commissionCreatedDateRange: null,
      commissionSettledDateRange: null,

      settlementSearchForm: {
        merchant_id: '',
        settlement_status: '',
        settlement_period: '',
        start_date: '',
        end_date: ''
      },
      settlementDateRange: null,

      // 选择项
      selectedCommissions: [],
      selectedSettlements: [],

      // 创建结算单对话框
      createSettlementDialogVisible: false,
      createSettlementForm: {
        merchant_id: '',
        settlement_period: 'monthly',
        campaign_id: '',
        start_date: '',
        end_date: '',
        allow_empty: false
      },
      createSettlementRules: {
        merchant_id: [
          { required: true, message: '请输入商户ID', trigger: 'blur' }
        ],
        settlement_period: [
          { required: true, message: '请选择结算周期', trigger: 'change' }
        ]
      },
      createSettlementDateRange: null,
      createSettlementLoading: false,

      // 结算详情对话框
      settlementDetailDialogVisible: false,
      currentSettlement: null,
      settlementCommissions: [],

      // 处理结算对话框
      processSettlementDialogVisible: false,
      processSettlementLoading: false,

      // 完成结算对话框
      completeSettlementDialogVisible: false,
      completeSettlementForm: {
        remark: ''
      },
      completeSettlementLoading: false,

      // 取消结算对话框
      cancelSettlementDialogVisible: false,
      cancelSettlementForm: {
        reason: ''
      },
      cancelSettlementRules: {
        reason: [
          { required: true, message: '请输入取消原因', trigger: 'blur' }
        ]
      },
      cancelSettlementLoading: false
    }
  },
  mounted() {
    this.loadStatsData()
  },
  methods: {

    // 加载统计数据
    async loadStatsData() {
      try {
        const response = await nfcCommissionAPI.getCommissionStats({})
        const stats = response.data?.stats || {}
        // 映射API字段到前端字段
        this.statsData = {
          total_commission: stats.total_amount || '0.00',
          pending_commission: stats.pending_amount || '0.00',
          settled_commission: stats.settled_amount || '0.00',
          settlement_count: stats.settled_count || 0
        }
      } catch (error) {
        console.error('加载统计数据失败：', error)
        // 设置默认值
        this.statsData = {
          total_commission: '0.00',
          pending_commission: '0.00', 
          settled_commission: '0.00',
          settlement_count: 0
        }
      }
    },

    // 标签页切换
    handleTabClick(tab) {
      this.activeTab = tab.name
    },

    // 获取佣金数据
    async fetchCommissionData(params) {
      const searchParams = {
        ...params,
        ...this.commissionSearchForm
      }
      
      const response = await nfcCommissionAPI.getCommissionRecords(searchParams)
      return {
        list: response.data,
        total: response.count
      }
    },

    // 获取结算数据
    async fetchSettlementData(params) {
      const searchParams = {
        ...params,
        ...this.settlementSearchForm
      }
      
      const response = await nfcCommissionAPI.getSettlements(searchParams)
      return {
        list: response.data,
        total: response.count
      }
    },

    // 处理日期范围变化
    handleCommissionCreatedDateRangeChange(value) {
      if (value && value.length === 2) {
        this.commissionSearchForm.created_start_date = value[0]
        this.commissionSearchForm.created_end_date = value[1]
      } else {
        this.commissionSearchForm.created_start_date = ''
        this.commissionSearchForm.created_end_date = ''
      }
      this.handleRefreshCommission()
    },

    handleCommissionSettledDateRangeChange(value) {
      if (value && value.length === 2) {
        this.commissionSearchForm.settled_start_date = value[0]
        this.commissionSearchForm.settled_end_date = value[1]
      } else {
        this.commissionSearchForm.settled_start_date = ''
        this.commissionSearchForm.settled_end_date = ''
      }
      this.handleRefreshCommission()
    },

    handleSettlementDateRangeChange(value) {
      if (value && value.length === 2) {
        this.settlementSearchForm.start_date = value[0]
        this.settlementSearchForm.end_date = value[1]
      } else {
        this.settlementSearchForm.start_date = ''
        this.settlementSearchForm.end_date = ''
      }
      this.handleRefreshSettlement()
    },

    handleCreateSettlementDateRangeChange(value) {
      if (value && value.length === 2) {
        this.createSettlementForm.start_date = value[0]
        this.createSettlementForm.end_date = value[1]
      } else {
        this.createSettlementForm.start_date = ''
        this.createSettlementForm.end_date = ''
      }
    },

    // 处理选择变化
    handleCommissionSelectionChange(selection) {
      this.selectedCommissions = selection
    },

    handleSettlementSelectionChange(selection) {
      this.selectedSettlements = selection
    },

    // 查看佣金详情
    handleViewCommissionDetail(row) {
      console.log('查看佣金详情：', row)
      this.$message.info('佣金详情功能开发中')
    },

    // 创建结算单
    handleCreateSettlement() {
      this.createSettlementDialogVisible = true
    },

    // 确认创建结算单
    async confirmCreateSettlement() {
      this.$refs.createSettlementForm.validate(async (valid) => {
        if (valid) {
          this.createSettlementLoading = true
          try {
            const params = { ...this.createSettlementForm }
            await nfcCommissionAPI.createSettlement(params)
            this.$message.success('结算单创建成功')
            this.createSettlementDialogVisible = false
            this.handleRefreshSettlement()
            this.loadStatsData()
          } catch (error) {
            this.$message.error('创建失败：' + error.message)
          } finally {
            this.createSettlementLoading = false
          }
        }
      })
    },

    // 查看结算详情
    async handleViewSettlementDetail(row) {
      try {
        const response = await nfcCommissionAPI.getSettlementDetails(row.id)
        this.currentSettlement = response.data.settlement
        this.settlementCommissions = response.data.commissions || []
        this.settlementDetailDialogVisible = true
      } catch (error) {
        this.$message.error('获取结算详情失败：' + error.message)
      }
    },

    // 处理结算
    handleProcessSettlement(row) {
      this.currentSettlement = { ...row }
      this.processSettlementDialogVisible = true
    },

    // 确认处理结算
    async confirmProcessSettlement() {
      this.processSettlementLoading = true
      try {
        await nfcCommissionAPI.processSettlement({
          settlement_id: this.currentSettlement.id
        })
        this.$message.success('结算处理成功')
        this.processSettlementDialogVisible = false
        this.handleRefreshSettlement()
        this.loadStatsData()
      } catch (error) {
        this.$message.error('处理失败：' + error.message)
      } finally {
        this.processSettlementLoading = false
      }
    },

    // 完成结算
    handleCompleteSettlement(row) {
      this.currentSettlement = { ...row }
      this.completeSettlementDialogVisible = true
    },

    // 确认完成结算
    async confirmCompleteSettlement() {
      this.completeSettlementLoading = true
      try {
        const params = {
          settlement_id: this.currentSettlement.id,
          remark: this.completeSettlementForm.remark
        }
        await nfcCommissionAPI.completeSettlement(params)
        this.$message.success('结算完成成功')
        this.completeSettlementDialogVisible = false
        this.handleRefreshSettlement()
        this.loadStatsData()
      } catch (error) {
        this.$message.error('完成失败：' + error.message)
      } finally {
        this.completeSettlementLoading = false
      }
    },

    // 取消结算
    handleCancelSettlement(row) {
      this.currentSettlement = { ...row }
      this.cancelSettlementDialogVisible = true
    },

    // 确认取消结算
    async confirmCancelSettlement() {
      this.$refs.cancelSettlementForm.validate(async (valid) => {
        if (valid) {
          this.cancelSettlementLoading = true
          try {
            const params = {
              settlement_id: this.currentSettlement.id,
              reason: this.cancelSettlementForm.reason
            }
            await nfcCommissionAPI.cancelSettlement(params)
            this.$message.success('结算取消成功')
            this.cancelSettlementDialogVisible = false
            this.handleRefreshSettlement()
            this.loadStatsData()
          } catch (error) {
            this.$message.error('取消失败：' + error.message)
          } finally {
            this.cancelSettlementLoading = false
          }
        }
      })
    },

    // 导出佣金数据（与保证金页一致：若有选中，先弹确认）
    async handleExportCommission() {
      try {
        // 构建导出参数，默认导出筛选结果
        const exportParams = {
          ...this.commissionSearchForm,
          export_type: 'commission',
          mode: 'filter'
        }

        // 如果有选中数据，提示用户选择导出方式
        if (this.selectedCommissions && this.selectedCommissions.length > 0) {
          const action = await this.$confirm(
            `检测到已选中 ${this.selectedCommissions.length} 条记录，请选择导出方式：`,
            '选择导出方式',
            {
              confirmButtonText: '导出选中记录',
              cancelButtonText: '导出筛选结果',
              distinguishCancelAndClose: true,
              type: 'info'
            }
          ).then(() => 'selected').catch(action => {
            if (action === 'cancel') return 'filter'
            return null // 关闭对话框
          })

          if (!action) return // 用户关闭弹窗
          if (action === 'selected') {
            exportParams.mode = 'selected'
            exportParams.ids = this.selectedCommissions.map(row => row.id)
          }
        }

        // 调用导出API
        this.$message.info('正在生成CSV文件，请稍候...')
        const response = await nfcCommissionAPI.exportCommissionData(exportParams)

        // 处理下载，统一使用工具方法
        const result = handleCSVExportResponse(response, 'NFC佣金记录.csv')
        if (result.success) {
          this.$message.success(`导出成功：${result.filename}`)
        } else {
          throw new Error(result.error)
        }
      } catch (error) {
        console.error('CSV导出失败:', error)
        // 详细错误处理
        let errorMessage = '导出失败'
        if (error && error.message && error.message.includes('cancel')) {
          // 用户点了取消键，按筛选结果导出逻辑已处理；这里主要防止误报
          return
        }
        if (error.response) {
          if (error.response.data && error.response.data.message) {
            errorMessage = error.response.data.message
          } else {
            errorMessage = `服务器错误: ${error.response.status}`
          }
        } else if (error.message) {
          errorMessage = error.message
        }
        this.$message.error(errorMessage)
      }
    },

    // 导出结算数据（与保证金页一致：若有选中，先弹确认）
    async handleExportSettlement() {
      try {
        // 构建导出参数，默认导出筛选结果
        const exportParams = {
          ...this.settlementSearchForm,
          export_type: 'settlement',
          mode: 'filter'
        }

        // 如果有选中数据，提示用户选择导出方式
        if (this.selectedSettlements && this.selectedSettlements.length > 0) {
          const action = await this.$confirm(
            `检测到已选中 ${this.selectedSettlements.length} 条记录，请选择导出方式：`,
            '选择导出方式',
            {
              confirmButtonText: '导出选中记录',
              cancelButtonText: '导出筛选结果',
              distinguishCancelAndClose: true,
              type: 'info'
            }
          ).then(() => 'selected').catch(action => {
            if (action === 'cancel') return 'filter'
            return null // 关闭对话框
          })

          if (!action) return // 用户关闭弹窗
          if (action === 'selected') {
            exportParams.mode = 'selected'
            exportParams.ids = this.selectedSettlements.map(row => row.id)
          }
        }

        // 调用导出API
        this.$message.info('正在生成CSV文件，请稍候...')
        const response = await nfcCommissionAPI.exportCommissionData(exportParams)

        // 处理下载，统一使用工具方法
        const result = handleCSVExportResponse(response, 'NFC结算记录.csv')
        if (result.success) {
          this.$message.success(`导出成功：${result.filename}`)
        } else {
          throw new Error(result.error)
        }
      } catch (error) {
        console.error('CSV导出失败:', error)
        // 详细错误处理
        let errorMessage = '导出失败'
        if (error && error.message && error.message.includes('cancel')) {
          // 用户点了取消键，按筛选结果导出逻辑已处理；这里主要防止误报
          return
        }
        if (error.response) {
          if (error.response.data && error.response.data.message) {
            errorMessage = error.response.data.message
          } else {
            errorMessage = `服务器错误: ${error.response.status}`
          }
        } else if (error.message) {
          errorMessage = error.message
        }
        this.$message.error(errorMessage)
      }
    },

    // 工具方法 - 基于结算状态判断佣金状态
    getCommissionStatusText(settlementId, settlementStatus) {
      if (!settlementId) {
        return '待结算'
      }
      const statusMap = {
        0: '待处理',
        1: '处理中',
        2: '已结算',
        3: '结算失败'
      }
      return statusMap[settlementStatus] || '未知'
    },

    getCommissionStatusTagType(settlementId, settlementStatus) {
      if (!settlementId) {
        return 'warning'
      }
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'danger'
      }
      return typeMap[settlementStatus] || 'info'
    },

    getSettlementStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '处理中',
        2: '已完成',
        3: '已失败'
      }
      return statusMap[status] || '未知'
    },

    getSettlementStatusTagType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'danger'
      }
      return typeMap[status] || 'info'
    },

    getSettlementPeriodText(period) {
      const periodMap = {
        'daily': '日结',
        'weekly': '周结',
        'monthly': '月结',
        'quarterly': '季结'
      }
      return periodMap[period] || period
    },

    // 重置表单
    resetCreateSettlementForm() {
      this.$refs.createSettlementForm && this.$refs.createSettlementForm.resetFields()
      this.createSettlementForm = {
        merchant_id: '',
        settlement_period: 'monthly',
        campaign_id: '',
        start_date: '',
        end_date: '',
        allow_empty: false
      }
      this.createSettlementDateRange = null
    },

    resetCompleteSettlementForm() {
      this.completeSettlementForm = { remark: '' }
    },

    resetCancelSettlementForm() {
      this.$refs.cancelSettlementForm && this.$refs.cancelSettlementForm.resetFields()
      this.cancelSettlementForm = { reason: '' }
    },

    // 搜索重置
    resetCommissionSearch() {
      this.commissionSearchForm = {
        merchant_id: '',
        campaign_id: '',
        settlement_status: '',
        min_amount: '',
        max_amount: '',
        created_start_date: '',
        created_end_date: '',
        settled_start_date: '',
        settled_end_date: ''
      }
      this.commissionCreatedDateRange = null
      this.commissionSettledDateRange = null
    },

    resetSettlementSearch() {
      this.settlementSearchForm = {
        merchant_id: '',
        settlement_status: '',
        settlement_period: '',
        start_date: '',
        end_date: ''
      }
      this.settlementDateRange = null
    },

    // 通用方法
    handleEdit() {
      // 编辑功能暂时不需要
    },

    handleDelete() {
      // 删除功能暂时不需要
    },

    handleRefreshCommission() {
      this.$refs.commissionTable && this.$refs.commissionTable.refresh()
    },

    handleRefreshSettlement() {
      this.$refs.settlementTable && this.$refs.settlementTable.refresh()
    }
  }
}
</script>

<style scoped>
.page-box {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-content {
  padding: 20px;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.settlement-actions {
  margin-bottom: 15px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: bold;
  min-width: 100px;
  color: #606266;
}

.amount {
  color: #409EFF;
  font-weight: 600;
}

.amount-text {
  color: #303133;
  font-weight: 600;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
